//
//  OAuthViewController.swift
//  SinaWeibo
//
//  Created by 石林 on 15/11/12.
//  Copyright © 2015年 石林. All rights reserved.
//

import UIKit
import SVProgressHUD


class OAuthViewController: UIViewController {

    let webView = UIWebView()
    
    
    func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func fullAccount() {
        let jsString = "document.getElementById('userId').value = 'iosshilin@gmail.com' , document.getElementById('passwd').value = 'sl329643976';"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        print(view)
        setupUI()
        
        loadOAuthPage()
        
    }
    
    private func loadOAuthPage() {
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }
    
    private func setupUI() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "fullAccount")
    }
    
    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        SVProgressHUD.dismiss()
    }

}
/*
Optional(https://api.weibo.com/oauth2/authorize?client_id=4069455568&redirect_uri=https://www.baidu.com/)
Optional(https://api.weibo.com/oauth2/authorize)
Optional(https://api.weibo.com/oauth2/authorize#)
Optional(https://api.weibo.com/oauth2/authorize)
Optional(https://www.baidu.com/?code=09c3bcc6a8ce4f01a7ee2c79f3be420c)
*/

extension OAuthViewController: UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
        
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
        
    }

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let urlString = request.URL?.absoluteString else{
            return false
        }
        
        //网页请求页面或网页授权页面
        if urlString.hasPrefix("https://api.weibo.com/") {
            
            return true
        }
        
        if !urlString.hasPrefix(redirect_uri) {
            return false
        }
        
        guard let query = request.URL?.query else {
            return false
        }
        print(query)
        
        let codeStr = "code="
        let code = query.substringFromIndex(codeStr.endIndex)
        
        print(code)
        
        UserAccountViewModel().loadAccessToken(code) { (error) -> () in
            
            print("come here")
            if error != nil {
                SVProgressHUD.showInfoWithStatus("堵车了( ⊙ o ⊙ )!!!")
                return
            }
//            self.dismissViewControllerAnimated(true, completion: nil)

//            NSNotificationCenter.defaultCenter().postNotificationName(AppSwitchRootViewControler, object: "Welcome")
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                NSNotificationCenter.defaultCenter().postNotificationName(AppSwitchRootViewControler, object: "Welcome")
            })
        }
        
        return false
    }
    
    
    
    
}
